<template>
  <Tabs>
    <TabPane label="登录信息">
      <Form ref="userInfo" :model="userInfo" :label-width="80" :rules="ruleInline">
        <FormItem label="用户名称" prop="username">
          <Input v-model="userInfo.username" placeholder="用户登录名称"></Input>
        </FormItem>
        <FormItem label="Email">
          <Input v-model="userInfo.email" placeholder="Email，用于接收系统消息"></Input>
        </FormItem>
        <FormItem label="手机号码">
          <Input v-model="userInfo.mobile" placeholder="手机号码，用于接收验证短信"></Input>
        </FormItem>
        <FormItem label="登录密码">
          <Input v-model="userInfo.password" placeholder="登录密码，不修改请留空"></Input>
        </FormItem>
        <FormItem label="逻辑删除">
          <Select v-model="userInfo.deleted_flag" style="width:200px">
            <Option v-for="item in [{value:1,label:'是'},{value:0,label:'否'}]" :value="item.value" :key="item.value">{{
              item.label }}
            </Option>
          </Select>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="post('userInfo',userInfo)">保存</Button>
        </FormItem>
      </Form>
    </TabPane>

    <TabPane label="扩展信息" v-if="isEditStatus">
      <Form ref="memberInfo" :model="memberInfo" :label-width="100" :rules="ruleInlineMemberInfo">
        <FormItem label="邀请码" prop="invitation_code">
          <Input v-model="memberInfo.invitation_code" :disabled="true"></Input>
        </FormItem>

        <FormItem label="腾讯QQ">
          <Input v-model="memberInfo.qq"></Input>
        </FormItem>

        <FormItem label="Github账号">
          <Input v-model="memberInfo.github"></Input>
        </FormItem>

        <FormItem label="知乎账号">
          <Input v-model="memberInfo.zhihu"></Input>
        </FormItem>

        <FormItem label="微博账号">
          <Input v-model="memberInfo.weibo"></Input>
        </FormItem>


        <FormItem>
          <Button type="primary" @click="post('memberInfo',memberInfo)">保存</Button>
        </FormItem>
      </Form>
    </TabPane>

    <TabPane label="角色信息" v-if="isEditStatus">
      <Form>
        <Tag v-for="role in roleInfo" :key="role.id" v-model="role.id" :name="role.id" type="border" closable
             color="primary"
             @on-close="removeRole">{{role.title}}
        </Tag>
        <Select v-model="role_id" style="width:200px;" size="small">
          <Option
            v-for="item in roleList"
            :value="item.value"
            :key="item.value"
          >{{ item.label }}
          </Option>
        </Select>
        <Button icon="ios-add" type="dashed" size="small" @click="doAddNewRole">添加角色</Button>

      </Form>
    </TabPane>


    <TabPane label="标签" v-if="isEditStatus">
      <Form>
        <Tag v-for="tag in tagInfo" :key="tag.id" v-model="tag.id" :name="tag.id" type="border" closable
             color="primary"
             @on-close="removeTag">{{tag.title}}
        </Tag>
        <Input v-model="newTag" size="small" style="width: 100px;"></Input>
        <Button icon="ios-add" type="dashed" size="small" @click="post('newTag',newTag)">添加标签</Button>

      </Form>
    </TabPane>
  </Tabs>


</template>
<script>
  import {role, user} from "@/api";
  import {
    Button,
    Form,
    FormItem,
    Input,
    InputNumber,
    Modal,
    Option,
    Radio,
    RadioGroup,
    Select,
    TabPane,
    Tabs,
    Tag
  } from "iview";
  import {mapGetters} from "vuex";

  export default {
    components: {
      InputNumber,
      Button,
      Form,
      FormItem,
      Input,
      Tabs,
      TabPane,
      RadioGroup,
      Radio,
      Select,
      Option,
      Tag,
      Modal
    },
    data() {
      return {
        role_id: 0,
        showAddRole: false,
        userInfo: {
          id: "",
          username: "",
          email: "",
          mobile: ""
        },
        ruleInline: {
          username: [{required: true, message: "用户名称必须填写", trigger: "blur"}],
          email: [{required: true, message: "Email必须填写", trigger: "blur"}],
          mobile: [{required: true, message: "手机号码必须填写", trigger: "blur"}]
        },
        ruleInlineMemberInfo: {
          qq: [{required: true, message: "QQ必须填写", trigger: "blur"}],
          // email: [{required: true, message: "Email必须填写", trigger: "blur"}],
          // mobile: [{required: true, message: "手机号码必须填写", trigger: "blur"}]
        },
        memberInfo: {
          uid: '',
          invitation_code: '',
          qq: '',
          weibo: '',
          zhihu: '',
          github: ''
        },
        roleInfo: {},
        tagInfo:{},
        roleList: [],
        newTag:'',
      };
    },

    methods: {
      post(type, data) {
        if (type === 'userInfo') {
          this.$refs["userInfo"].validate(valid => {
            if (valid) {
              if (this.userInfo.id) {
                //更新数据
                user.update(this.userInfo.id, this.userInfo).then(res => {
                  if (res.errno !== 0) {
                    this.$Message.error(res.errmsg);
                  } else {
                    this.$router.push("/ucenter/user/list");
                  }
                });
              } else {
                //新增数据
                user.create(this.userInfo).then(res => {
                  if (res.errno !== 0) {
                    this.$Message.error(res.errmsg);
                  } else {
                    this.$router.push("/ucenter/user/list");
                  }
                });
              }
            } else {
              this.$Message.error("请填写必要信息");
            }
          });
        } else if (type === "memberInfo") {

          this.$refs["memberInfo"].validate(valid => {

            console.log(this.memberInfo);

            if (valid) {
              if (this.memberInfo.uid) {

                //更新数据
                user.updateMemberInfo(this.memberInfo.uid, this.memberInfo).then(res => {
                  if (res.errno !== 0) {
                    this.$Message.error(res.errmsg);
                  } else {
                    this.$router.push("/ucenter/user/list");
                  }
                });
              }
            } else {
              this.$Message.error("请填写必要信息");
            }
          });
        } else if (type === "newTag") {

          let uid = this.userInfo.id;

          if (this.newTag && uid) {
            let formData={
              uid:uid,
              tag: this.newTag,
            };
            user.addTag(formData).then(res => {
              this.newTag='';
              this.get(this.userInfo.id);
            });
          }

        }
      },
      get(id) {
        user.getInfo(id, {}).then(res => {
          // console.log(this.userInfo);
          this.userInfo = res.data;
          this.roleInfo = res.data.roles;
          this.tagInfo=res.data.tags;
        });

        user.getMemberInfo(id).then(res => {
          this.memberInfo = res.data;
        });
      },
      removeTag(event, name) {
        console.log(name);
        const tag_id = name;
        const user_id = this.userInfo.id;
        user.deleteTag(user_id,tag_id).then(res => {
          //this.get(this.userInfo.id);
          //避免重新加载
          const index = this.tagInfo.findIndex((tag) => {
            return tag.id === name;
          });
          this.tagInfo.splice(index, 1)
        });
      },
      removeRole(event, name) {
        console.log(name);
        const role_id = name;
        const user_id = this.userInfo.id;
        role.deleteUser(role_id, user_id).then(res => {
          //this.get(this.userInfo.id);
          const index = this.roleInfo.findIndex((role) => {
            return role.id === name;
          });
          this.roleInfo.splice(index, 1)
        });
      },
      doAddNewRole() {
        let role_id = this.role_id;
        let uid = this.userInfo.id;

        if (role_id && uid) {
          // let formData = new FormData();
          // formData.append('uid', uid);
          // formData.append('role_id', role_id);

          let formData={
            uid:uid,
            role_id:role_id,
          };
          role.addUser(formData).then(res => {
            this.get(this.userInfo.id);
          });
        }

      },
      async getRoleList() {
        this.loading = true;
        const map = {page: 0};
        let data = await role.getList(map);
        this.roleList = data.data.map(item => {
          return {
            value: item.id,
            label: `[${item.name}]${item.title}`
          };
        });
        this.roleList.unshift({value: "0", label: "请选择角色"});
        this.loading = false;
      },
    },
    computed: {
      isEditStatus(){
        return this.userInfo.id!=""

      }
    },
    async mounted() {
      if(this.$route.query.id) {
        this.get(this.$route.query.id);
      }

      await this.getRoleList();
    }
  };
</script>
